package icu.lookyousmileface.boot_reactorweb_gettinggide;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.UUID;

/**
    * @author gcq
　　* @description: TODO
　　* @date 2020/12/31 11:20 下午
　　*/
@SpringBootApplication
public class BootReactorwebGettinggideApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootReactorwebGettinggideApplication.class, args);
    }

    @RestController
    class ReactorController{
        /**
         * <div>使用FLux</div>
         * @return Flux
         */
        @GetMapping("/flux")
        public Flux<String> helloFlux(){
            return Flux.just("Hello,ReactorWeb-Flux!");
        }

        /**
         * <div>使用Mono</div>
         * @return Mono
         */
        @GetMapping("/mono")
        public Mono<String> helloMono(){
            return Mono.just("Hello,ReactorWeb-Mono!");
        }

        /**
         * <div>模拟服务端SSE，向客户端定时推送事件流</div>
         * <div>MediaType.TEXT_EVENT_STREAM_VALUE 指定媒体类型<b>Content-Type</b>为<b>text/event-stream</b></div>
         * @return Flux
         */
        @GetMapping(value = "/taskFlux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<String> taskFlux(){
            //interval表示间隔多久发送一个流
            return Flux.interval(Duration.ofMillis(1000)).map(value->" ->"+value);
        }

        /**
         * <div>Server-Sent-Event</div>
         *<div>使用返回值为ServerSentEvent则无需指定Content-Type为指定evnet-stream</div>
         * <div>CrossOrigin表示跨域，使用的html不在一个工程之中</div>
         * @return Flux<ServerSentEvent<String>>
         */
        @CrossOrigin
        @GetMapping("/see")
        public Flux<ServerSentEvent<String>> sse(){
            return Flux.interval(Duration.ofMillis(1000)).map(val->{
               return ServerSentEvent.
                       <String>builder()
                       //id可为空
//                       .id(UUID.randomUUID().toString())
                        //事件可为空
                       .event("SSE_EVENT")
                       .data(val.toString())
                       .build();
            });
        }
    }
}
